'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken')

class HomeController extends Controller {
  async login() {
    const { ctx, app } = this;
    
    // 获取由前端传来的参数
    const { username, password } = ctx.request.body;

    // 去数据库中验证
    const data = await app.mysql.get('userlist', {username, password})

    if(data) {
        ctx.body = {
            code: 1,
            token: jwt.sign(data.id, '1907A')
        }
    } else {
      ctx.status = 401
        ctx.body = {
            code:0,
            msg: '用户名或者密码错误'
        }
    }
  }

  async user() {
    // ctx: context, request(请求对象，前端),response(响应对象，后端)
    const { ctx, app } = this;

    // 获取token
    const { authorization } = ctx.request.headers;

    // 解密token
    try {
        const token = jwt.verify(authorization, '1907A')

        const data = await app.mysql.get('userlist', {id: token})

        ctx.body = {
          code: 1,
          data
        }

    } catch (error) {
        ctx.status = 401;

        ctx.body = {
          code: 0,
          msg: '登录已过期 请重新登录'
        }
    }


  }
}

module.exports = HomeController;
